import { Button, Modal, Input, Tree, Icon, Avatar, Checkbox,message } from 'antd';
import React, {useState, useEffect} from 'react';
import { Scrollbars } from 'react-custom-scrollbars';
import styles from './ObjectOfApproval.less';
import { useRequest } from '@umijs/hooks';
import { getTreeData, handleAudit, getTreeUser } from '../../service';
import { aesEncrypt } from '@/config/cryptoService'; // 加密

const { TreeNode } = Tree;

const ObjectOfApproval = props => {

  const { approvalData, approvalVisible, handleApprovalVisible, onSuccess } = props;

  const [rightKeys, handleRightKeys] = useState([]);

  // 存储右侧选中的数据
  const [rightData, handleRightData] = useState([]);

  // 树形数据
  const [treeData, handleTreeData] = useState([]);
  // 列表数据
  const [listData, handleListData] = useState([])
  // 选中的key
  const[checkedKeys, handleKeys] = useState([])

  // 人员列表---选择的人员数据
  const[selectedItemIds, setSelectedItemIds] = useState([])
  const[selectedItems, setSelectedItems] = useState([])
  //搜索框loading
  const [loadingSearch, handleLoadingSearch] = useState(false)
  // 是否展示树
  const [showTree, handleShowTree] = useState(true);

  const [btnLoading, handleBtnLoading] = useState(false)

  const {run} = useRequest((params) => getTreeData(params), {
    manual: true,
    onSuccess: data => {
      handleTreeData(data.depars)
    }
  })

  useEffect(() => {
    if (approvalVisible) {
      run('1');
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [approvalVisible])

  const renderTreeNodes = data => {
    return data.map(item => {
      if (item.children) {
        return (
          <TreeNode checkable={false}  title={item.toFname} key={item.id || item.toId} dataRef={item}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      
      if (item.isLeaf) {
        return (
          <TreeNode
            isLeaf={true} photo={item.photo} key={item.id || item.toId} tuno={item.tuno} isTitle={item.toFname} 
            title={[
              <div key={item.id || item.toId} className={styles.item}>
                <span className={styles.avatar}>
                <Avatar
                  shape="avatar"
                  icon={item.photo ? false : 'user'}
                  src={item.photo ? `data:image/png;base64,${item.photo}` : false}
                />
                </span>
                <div className={styles.personInfo}>
                <span>{item.toFname}</span>
                </div>
              </div>
            ]}
          />
        )
      } else {
        return <TreeNode checkable={false} key={item.id || item.toId} title={item.toFname} dataRef={item} />;
      }
    });
  }
  
  const onLoadData = treeNode => {
    return new Promise(resolve => {
      if (treeNode.props.children) {
        resolve();
        return;
      }
      getTreeData(treeNode.props.dataRef.toId).then(res=>{
          if (res.depars.length && !res.emps.length) {
            treeNode.props.dataRef.children = res.depars;
            console.log('有部门无人员');
          } else if (!res.depars.length && res.emps.length) {
            console.log('有人员无部门');
            treeNode.props.dataRef.children = res.emps.map(v=>{
              return {
                id: v.id,
                toFname: v.tuCname,
                isLeaf: true,
                tuno:v.tuno,
                photo: v.photo
              }
            });
          } else if (res.depars.length && res.emps.length) {
            console.log('有人员有部门');
            let tempEmps = res.emps.map(v=>{
              return {
                id: v.id,
                toFname: v.tuCname,
                isLeaf: true,
                tuno:v.tuno,
                photo: v.photo
              }
            })
            treeNode.props.dataRef.children = [...res.depars, ...tempEmps]
          }
          handleTreeData([...treeData]);
          resolve();
      })
    });
  }
  // 搜索
  const searchVal = (value, event) => {
    getTreeUser({keySearch:value}).then(res => {
      let tempL = []
      res.map(item => {
        
        tempL.push({
          tuNo: item.tuNo,
          id: item.id,
          tuCname: item.tuCname,
          photo: item.photo
        })
      })
      tempL.map(item => item.checked = false)
      handleListData(tempL)
    })

  }

  //勾选树形结构 人员
  const onCheck = (checkedKeys, e) => {
    if (checkedKeys === localStorage.getItem('id')) {
      message.error("下一级审核人不能选择当前登录人")
      return false
    }
    let keys = checkedKeys.concat(rightKeys);
    handleKeys(checkedKeys);
    handleRightKeys(Array.from(new Set(keys)));
    console.log(e.checkedNodes);
    handleRightData(e.checkedNodes.map(v=>{
      return {
        tuNo: v.props.tuno,
        id: v.key,
        title: v.props.isTitle,
        photo: v.props.photo
      }
    }));
  }
  
  // 取消右侧已选人员
  const closeItem = (id) => {
    handleRightData(rightData.filter(v=>{
      return (v.id)!==id
    }))
    handleKeys(checkedKeys.filter(v=> {
      return v!==id
    }))
    handleRightKeys(rightKeys.filter(v=>{
      return v!==id
    }))

  }
  // 点击左侧列表
  const changeItem = val => {
    if (val.id === localStorage.getItem('id')) {
      message.error("下一级审核人不能选择当前登录人")
      return false
    }
    if (!~rightKeys.indexOf(val.id)){
      handleRightData(pre => pre.concat([val]))
      handleRightKeys(pre => pre.concat([val.id]))
      handleKeys(pre => pre.concat([val.id]))
    } else {
      handleRightData(pre => pre.filter(a => {
        return a.id !== val.id
      }))
      handleRightKeys(pre => pre.filter(id => id !== val.id))
      handleKeys(pre => pre.filter(id => id !== val.id))
    }
  }

  const sureDept = () => {
    if (rightData.length === 0) {
      message.error("请选择审核人员")
    } else {
      const hide = message.loading('正在提交')
      handleBtnLoading(true)
      let arr = rightData.map(item => item.tuNo).join(',')
      const encryptParams = JSON.parse(JSON.stringify(arr));
      // 加密
      let encryptParams1 = aesEncrypt(encryptParams);

      handleAudit({...approvalData, handleUser:encryptParams1}).then(res=>{
        onSuccess(res)
        hide()
        handleBtnLoading(false)
        handleApprovalVisible(false)
      }).catch(err =>{
        hide()
        handleBtnLoading(false)
      })
    }
  }
  return (
      <Modal
        destroyOnClose={true}
        wrapClassName={styles.approvalObject}
        onCancel={()=>{handleApprovalVisible(false)}}
        footer={null}
        width={618}
        title='选择审批对象'
        visible={approvalVisible}
        // visible={true}
      >
        <div className={styles.tree}>
          <div className={styles.left}>
            <div className={styles.searchBox}>
              <Input.Search  placeholder="搜索姓名/工号" 
                loading={loadingSearch}
                allowClear={true}
                onChange={(e)=>{
                  if (e.target.value.length < 1){
                    handleShowTree(true)
                  }
                }}
                onSearch={(value, event)=>{
                  handleShowTree(false)
                  searchVal(value, event)
                }}
                enterButton />
            </div>
            <div className={styles.content}>
              <Scrollbars autoHide style={{height: "100%", width: "100%"}}>
                <div style={{display: showTree?'block':'none'}}>
                  <Tree
                      checkedKeys={checkedKeys}
                      checkable={true}
                      selectable={false}
                      showLine={true}
                      onCheck={onCheck}
                      className="hide-file-icon"
                      loadData={onLoadData}
                    >
                      {renderTreeNodes(treeData)}
                    </Tree>
                </div>


                <div style={{display: showTree?'none':'block'}} className={styles.userList}>
                    <Checkbox.Group value={rightKeys} style={{ width: '100%' }}>
                      {listData.map(v=>{
                        return (
                          <div key={v.id} style={{paddingTop: '10px'}} className={styles.userItem} >
                            <span className={styles.avatar}>
                            <Avatar
                              shape="avatar"
                              icon={v.photo ? false : 'user'}
                              src={v.photo ? `data:image/png;base64,${v.photo}` : false}
                            />
                            </span>
                            <div className={styles.personInfo}>
                              <span>{v.tuCname}</span>
                            </div>
                            <Checkbox value={v.id} onClick={()=>{changeItem(v)}}></Checkbox>
                          </div>
                        )
                      })}
                    </Checkbox.Group>
                  </div>
              </Scrollbars>
            </div>
          </div>
          <div className={styles.right}>
            <div className={styles.rightTitle}>已选择对象</div>
            <div className={styles.content}>
              <Scrollbars autoHide style={{height: "100%", width: "100%"}}>
                {rightData.map(v=>{
                  return (
                    <div key={v.tuNo} style={{paddingTop: '10px'}} className={styles.item}>
                      <span className={styles.avatar}>
                      <Avatar
                        shape="avatar"
                        icon={v.photo ? false : 'user'}
                        src={v.photo ? `data:image/png;base64,${v.photo}` : false}
                      />
                      </span>
                      <div className={styles.personInfo}>
                      <span>{v.title || v.tuCname}</span>
                      </div>
                      <span onClick={() => {closeItem(v.id)}} style={{cursor: 'pointer'}} className={styles.checkT}>
                        <Icon type="close-circle" />
                      </span>
                    </div>
                  )
                })}
              </Scrollbars>
            </div>
          </div>
        </div>
        <div style={{textAlign: "right", padding: "10px 10px"}}>
          <Button onClick={()=>{handleApprovalVisible(false)}} loading={btnLoading}>关闭</Button>
          &nbsp;&nbsp;
          <Button onClick={()=>{sureDept()}} type="primary" loading={btnLoading}>确定</Button>
        </div>
      </Modal>
  )
}

export default ObjectOfApproval;
